﻿using Consul;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;

namespace ConsulDemo
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            RegisterToConsule();
        }

        protected void Application_End()
        {
            _consuleClient.Agent.ServiceDeregister(_serviceId);
        }

        private string _serviceId;
        private IConsulClient _consuleClient;

        private void RegisterToConsule()
        {
            var config = new Consul.ConsulClientConfiguration();
            config.Address = new Uri("http://localhost:8500");
            _consuleClient = new Consul.ConsulClient(config);


            var host = "localhost";
            var port = 59401;

            _serviceId = "Service-v1-" + Dns.GetHostName() + "-" + host + ":" + port;

            var serviceRegistration = new AgentServiceRegistration()
            {
                ID = _serviceId,
                Address = host,
                Port = port,
                Name = "Service",
                Tags = new[] { "API1" },
                Check = new AgentServiceCheck
                {
                    HTTP = "http://" + host + ":" + port + "/api/demo",
                    Interval = TimeSpan.FromSeconds(5),
                    Timeout = TimeSpan.FromSeconds(2)
                }
            };

            _consuleClient.Agent.ServiceRegister(serviceRegistration);
        }
    }
}